package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.domain.OrderDetail;
import com.itheima.reggie.domain.Order;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    CartService cartService;
    @Override//后端订单列表
    public Page<Order> findByPage(Integer pageNum, Integer pageSize, String number, Date beginTime, Date endTime) {
        Page<Order> page=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(number), Order::getNumber,number);
        wrapper.orderByDesc(Order::getOrderTime);
        wrapper.ge(beginTime!=null, Order::getOrderTime,beginTime).le(endTime!=null, Order::getOrderTime,endTime);
        page = orderMapper.selectPage(page, wrapper);
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(OrderDetail::getOrderId,order.getId());
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
                order.setOrderDetails(orderDetails);
            }
        }
        return page;
    }
    //提交订单
    @Override
    public void submit(Order order) {
        List<Cart> cartList = cartService.cartList();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车为空不能下单");
        }
        Address address = addressMapper.selectById(order.getAddressId());
        if (address==null) {
            throw new CustomException("收货地址为空不能下单");
        }
        long id = IdWorker.getId();
        BigDecimal price=new BigDecimal(0);
        for (Cart cart : cartList) {
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setImage(cart.getImage());
            orderDetail.setName(cart.getName());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setOrderId(order.getId());
            orderDetailMapper.insert(orderDetail);
            price=price.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }
        order.setNumber(String.valueOf(id));
        order.setId(id);
        //TODO 教学模式，设计随机订单状态，用于测试后台点击派送和完成功能，以及h5端再来一单功能
        order.setStatus(new Random().nextInt(4)+1);
        order.setUserId(UserHolder.get().getId());
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());
        order.setAmount(price);
        StringBuilder sb=new StringBuilder();
        sb.append(StrUtil.isNotEmpty(address.getProvinceName())?address.getProvinceName():"");
        sb.append(StrUtil.isNotEmpty(address.getCityName())?address.getCityName():"");
        sb.append(StrUtil.isNotEmpty(address.getDistrictName())?address.getDistrictName():"");
        sb.append(StrUtil.isNotEmpty(address.getDetail())?address.getDetail():"");
        order.setAddress(sb.toString());
        order.setPhone(address.getPhone());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);
        cartService.cartClean();
    }
    //H5查看历史订单
    @Override
    public Page<Order> findOrderByPage(Integer pageNum, Integer pageSize) {
        Page<Order> page=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,UserHolder.get().getId());
        wrapper.orderByDesc(Order::getOrderTime);
        page=orderMapper.selectPage(page,wrapper);
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(OrderDetail::getOrderId,order.getId());
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
                order.setOrderDetails(orderDetails);
            }
        }
        return page;
    }
    //查看所有订单
    @Override
    public List<Order> findList() {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,UserHolder.get().getId());
        List<Order> order = orderMapper.selectList(wrapper);
        return order;
    }
    // 再来一单
    @Override
    public void againAdd(Long id) {
        //以下代码直接下了重复订单
       /* Orders order = orderMapper.selectById(id);
        order.setId(null);
        order.setStatus(1);
        order.setNumber(IdUtil.createSnowflake(1,1).nextId()+"");
        orderMapper.insert(order);
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(orderDetails)) {
            for (OrderDetail orderDetail : orderDetails) {
                orderDetail.setOrderId(order.getId());
                orderDetail.setId(null);
                orderDetailMapper.insert(orderDetail);
            }
        }*/
       //以下代码，将当前订单菜品重新加入购物车，并未下单，需要用户手动提交
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(orderDetails)) {
            throw new CustomException("订单发生了错误，可能已被删除");
        }
        for (OrderDetail orderDetail : orderDetails) {
            Cart cart = new Cart();
            cart.setName(orderDetail.getName());
            cart.setUserId(UserHolder.get().getId());
            cart.setDishId(orderDetail.getDishId());
            cart.setSetmealId(orderDetail.getSetmealId());
            cart.setDishFlavor(orderDetail.getDishFlavor());
            cart.setNumber(orderDetail.getNumber());
            cart.setAmount(orderDetail.getAmount());
            cart.setImage(orderDetail.getImage());
            cart.setCreateTime(new Date());
            cartMapper.insert(cart);
        }
    }

    @Override
    public void sendOrder(Order order) {
        orderMapper.updateById(order);
    }
}
